package com.educate.upms.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.upms.dao.UpmsOrganizationDao;
import com.educate.upms.model.bo.UpmsOrganizationBO;
import com.educate.upms.model.po.UpmsOrganization;
import com.educate.upms.rpc.api.UpmsOrganizationService;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class UpmsOrganizationServiceImpl implements UpmsOrganizationService {

    @Resource UpmsOrganizationDao upmsOrganizationDao;

    @Override
    public void create(UpmsOrganizationBO bo) {
        upmsOrganizationDao.insert(bo);
    }

    @Override
    public void delete(UpmsOrganizationBO bo) {
        upmsOrganizationDao.delete(bo);
    }

    @Override
    public void delete(String upmsOrganizationId) {
        upmsOrganizationDao.deleteById(upmsOrganizationId);
    }

    @Override
    public UpmsOrganizationBO detail(String upmsOrganizationId) {
        Optional<UpmsOrganization> optional = upmsOrganizationDao.findById(upmsOrganizationId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new UpmsOrganizationBO(optional.get());
    }

    @Override
    public UpmsOrganizationBO detail(UpmsOrganizationBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(UpmsOrganizationBO bo) {
        Optional<UpmsOrganization> optional = upmsOrganizationDao.findById(bo.getUpmsOrganizationId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        upmsOrganizationDao.save(optional.get());
    }

    @Override
    public Page<UpmsOrganizationBO> query(UpmsOrganizationBO bo, PageRequest pageRequest) {
        return upmsOrganizationDao.query(bo, pageRequest).map(UpmsOrganizationBO::new);
    }

    @Override
    public List<UpmsOrganizationBO> list(UpmsOrganizationBO bo) {
        List<UpmsOrganization> result = upmsOrganizationDao.findAll();
        return ListUtils.map(result, UpmsOrganizationBO::new);
    }
}
